const chalk = require("chalk");
const { execSync } = require("child_process");
const download = require("download-git-repo");
const ora = require("ora");
const spinner = ora("Loading undead unicorns");

const config = require("../../config/config.js");

const fs = require("fs-extra");
const path = require("path");

/**
 * 获取目标仓库所有分支
 * @returns
 */
const getGitBranchs = () => {
  /**
   * 同步操作
   * execSync 用于执行命令的
   */
  try {
    /**
     * git ls-remote --heads <remote>
     * 该命令使用于查询某个 远程仓库 的所有分支
     *
     * 获取执行命令的结果
     */
    const output = execSync(
      `git ls-remote --heads ${config.cloneGitRemoteUrl}`
    );

    // Buffer 格式转字符串
    const stdout = output.toString();

    /**
     * 获取所有分支
     */
    const branches = stdout.split("\n").map((line) => line.split("\t")[1]);

    return branches
      .filter((branch) => !!branch)
      .map((branch) => branch.split("/")[2])
      .filter((branch) => branch !== "master");
  } catch (err) {
    console.log(err);
  }
};

/**
 * 克隆目标仓库代码
 * @param {*} gitRemote
 * @param {*} appName
 * @returns
 */
const downloadGit = (gitRemote = "", appName = "") => {
  spinner.start("开始初始化");

  return new Promise((resolve, reject) => {
    download(
      "direct:" + gitRemote,
      appName,
      {
        clone: true,
      },
      (err) => {
        if (err) {
          spinner.fail(chalk.green("初始化失败 \n" + err));
          return reject("拉取模板失败");
        } else {
          spinner.succeed(chalk.green(`初始化成功`));
          // fs.remove(path.join(process.cwd(), appName))
          return resolve();
        }
      }
    );
  });
};

module.exports = {
  getGitBranchs,
  downloadGit,
};
